/**  
 * All rights Reserved, Designed By <a href="www.itttq.com" target="_blank">www.itttq.com</a>
 * @date:   2018-01-6 11:42:21
 * @Copyright: 2017 <a href="www.itttq.com" target="_blank">www.itttq.com</a> Inc. All rights reserved. 
 */
package com.itttq.gshop.h5.controller.order;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.itttq.gshop.domain.po.OrderInfoPo;
import com.itttq.gshop.domain.po.PayMethodPo;
import com.itttq.gshop.domain.po.UserCartPo;
import com.itttq.gshop.domain.po.UserInfoPo;
import com.itttq.gshop.domain.to.OrderTo;
import com.itttq.gshop.domain.to.PageParamTo;
import com.itttq.gshop.domain.to.ResultPageTo;
import com.itttq.gshop.domain.to.ResultTo;
import com.itttq.gshop.generic.cmpt.annotation.Auth;
import com.itttq.gshop.generic.connector.IOrderInfoConnector;
import com.itttq.gshop.generic.connector.IOrderWareConnector;
import com.itttq.gshop.generic.connector.IPayMethodConnector;
import com.itttq.gshop.generic.controller.GenericController;
import com.itttq.gshop.generic.util.Constants;
import com.itttq.gshop.generic.util.Constants.InvoiceType;
import com.itttq.gshop.generic.util.Constants.OrderStatus;
import com.itttq.gshop.generic.util.Constants.Source;
@Auth
@RestController
@RequestMapping("order")
public class OrderController extends GenericController {
	private static final long serialVersionUID = 456162093189751748L;
	@Autowired
	private IOrderInfoConnector orderInfoConnector;
	@Autowired
	private IOrderWareConnector orderWareConnector;
	@Autowired
	private IPayMethodConnector payMethodConnector;
	
	/**
	 * 根据条件查询OrderInfoPo对象，并分页
	 * 
	 * @param order		查询的订单对象
	 * @param request	
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("list.html")
	public ModelAndView getOrders(OrderInfoPo order, HttpServletRequest request) {
		ModelAndView mv = getOrderInfos(order, request);
		mv.setViewName("/mine/orders");
		return mv;
	}

	/**
	 * 根据条件查询订单数据，并组装数据展示页面返回。<br>
	 * 即分页时调用此方法获取页面内容在前端展示
	 * 
	 * @param order
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("orders.html")
	public ModelAndView getOrderInfos(OrderInfoPo order, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/mine/orders-content");
		PageParamTo ppt = null == request ? new PageParamTo() : getPageParam(request);
		order.setStart(ppt.getStart());
		order.setSize(ppt.getSize());
		order.setUserId(this.getUserIdFromSession(request));
		ResultPageTo<OrderTo> rpt = orderInfoConnector.getOrders(order);
		mv.addObject("orders", rpt.getData());
		mv.addObject("sources", Source.values());
		mv.addObject("status", OrderStatus.values());
		mv.addObject("order", order);
		// 获取订单商品记录
		return mv;
	}
	
	private OrderInfoPo getOrderParam(OrderStatus os, HttpServletRequest request) {
		OrderInfoPo order = new OrderInfoPo();
		order.setStatus(os.getVal());
		order.setUserId(this.getUserIdFromSession(request));
		return order;
	}
	
	/**
	 * 根据条件查询未付款订单，并分页
	 * 
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("unpay.html")
	public ModelAndView unpayOrder(HttpServletRequest request) {
		return getOrders(getOrderParam(OrderStatus.UNPAID, request), request);
	}
	
	/**
	 * 根据条件查询已付款待发货订单，并分页
	 * 
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("paid.html")
	public ModelAndView paidOrderInfos(HttpServletRequest request) {
		return getOrders(getOrderParam(OrderStatus.PAID, request), request);
	}
	
	/**
	 * 根据条件查询已取消订单，并分页
	 * 
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("canceled.html")
	public ModelAndView canceledOrders(HttpServletRequest request) {
		return getOrders(getOrderParam(OrderStatus.CANCELED, request), request);
	}

	/**
	 * 跳转到查看页面
	 * @param id
	 * @return
	 */
	@RequestMapping("{id}.html")
	public ModelAndView viewOrderInfo(@PathVariable("id") Integer id) {
		ModelAndView mv = new ModelAndView("/mine/order");
		mv.addObject("info", orderInfoConnector.getOrderInfo(id));
		mv.addObject("invoiceTypes", InvoiceType.values());
		mv.addObject("sources", Source.values());
		// 获取订单商品
		mv.addObject("wares", orderWareConnector.getOrderWareByOrderId(id));
		return mv;
	}

	/**
	 * 生成订单，并去支付
	 * 
	 * @param id	订单ID
	 * @param status	订单更新后的状态
	 * @param op	操作类型
	 * @param remark	备注
	 * @Author 迷蝶
	 * @return ResultTo
	 * @throws Exception 
	 */
	@RequestMapping("create.html")
	public ModelAndView createOrder(OrderInfoPo order, HttpServletRequest request) throws Exception {
		ModelAndView mv = new ModelAndView("redirect:/cart/settlement.html");
		// 从Session获取购物车信息
		Object obj = this.getSession(request, Constants.SESSION_CART);
		if(null == obj || obj.toString().equals("[]")) {
			mv.addObject("code", ResultTo.BUSINESS_ERR);
			mv.addObject("msg", "生成订单出现数据错误！");
		} else {
			@SuppressWarnings("unchecked")
			List<UserCartPo> carts = (List<UserCartPo>) obj;
			order.setCarts(carts);
			UserInfoPo user = this.getUserFromSession(request);
			order.setUserId(user.getId());
			order.setUserName(user.getUsername());
			ResultTo rt = orderInfoConnector.createOrder(order);
			mv.addObject("code", rt.getCode());
			mv.addObject("msg", rt.getMsg());
			if(rt.getCode() == ResultTo.SUCCESS) {
				mv = gotoPay(Integer.valueOf(rt.getMsg()));
				// 清空SESSION
				this.getSession(request).removeAttribute(Constants.SESSION_CART);
			} else if(rt.getCode() == ResultTo.ORDER_WARE_NUM) {
				mv.addObject("msg", "以下商品库存不足：<br>" + rt.getMsg());
			}
		}
		return mv;
	}
	
	/**
	 * 跳转到订单选择支付页面<br>
	 * 如果是线下支付，直接为支付成功并更新订单状态。<br>
	 * 线上支付则跳转到第三方
	 * 
	 * @param orderId		订单ID
	 * @param payMethodId		支付方式ID。写死id=1为线下支付
	 * @Author 迷蝶
	 * @return ResultTo
	 */
	@RequestMapping("pay/{orderId}.html")
	public ModelAndView gotoPay(@PathVariable("orderId") int orderId) {
		ModelAndView mv = new ModelAndView("/order/payment");
		// 获取可用的支付方式
		PayMethodPo payMethod = new PayMethodPo();
//			payMethod.setStart(Constants.STATUTS_OPEN);
		mv.addObject("payMethods", payMethodConnector.getPayMethods(payMethod).getData());
		mv.addObject("order", orderInfoConnector.getOrderInfo(orderId));
		mv.setViewName("/order/payment"); // 跳转到支付页面
		return mv;
	}

	/**
	 * 根据订单ID更新订单状态，并记录到订单操作记录。<br>
	 * 订单变化限制如下：前面的状态必须由后面的状态变化而来
	 * 待支付1：无<br>
	 * 待发货2：<--待支付1；<br>
	 * 待收货3：<--待发货2；<br>
	 * 已完成4：<--待收货3；<br>
	 * 已取消5：<--待支付1；<br>
	 * 申请退款7：<--待发货2、退货中12；<br>
	 * 退款中8：<--申请退款7；<br>
	 * 已退款9：<--退款中8；<br>
	 * 退款失败10：<--申请退款7；<br>
	 * 申请退货11：<--待收货3；<br>
	 * 退货中12：<--申请退货11；<br>
	 * 退货失败15：<--申请退货11；<br>
	 * 删除16：<--已完成4、已取消5、已退款9、退款失败10、退货失败15<br>
	 * 取消退款：<--申请退款7<br>
	 * 取消退货：<--申请退货11
	 * 
	 * @param id	订单ID
	 * @param status	订单更新后的状态
	 * @param op	操作类型
	 * @param remark	备注
	 * @Author 迷蝶
	 * @return ResultTo
	 */
	@RequestMapping("status/{id}.html")
	public ResultTo updateOrderStatus(HttpServletRequest request, @PathVariable("id")int id, 
			String status, String op, String remark) {
		UserInfoPo user = this.getUserFromSession(request);
		return orderInfoConnector.updateOrderStatus(id, status, op, remark, user.getId(), user.getUsername());
	}
}